/*
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree {3,9,20,#,#,15,7},
    3
   / \
  9  20
    /  \
   15   7
return its zigzag level order traversal as:
[
  [3],
  [20,9],
  [15,7]
]
*/

class Solution {
public:
    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
        vector<vector<int> >res;
        if (!root) return res;
        queue<TreeNode *>cur, next;
        cur.push(root);
        while (!cur.empty()) {
            vector<int> resone;
            // traverse current level
            while (!cur.empty()) {
                TreeNode *n = cur.front(); cur.pop();
                resone.push_back(n->val);
                if (n->left) next.push(n->left);
                if (n->right) next.push(n->right);
            }
            if (res.size() % 2) { // reverse at even levels
                reverse(resone.begin(), resone.end());
            }
            res.push_back(resone);
            swap(cur, next);
        }
        return res;        
    }
};

#if 0
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
        vector<vector<int> > res;
        if (!root) return res;
        stack<TreeNode *> s1;
        stack<TreeNode *> s2;
        int level = 1;
        s1.push(root);
        while (!s1.empty()) {
            vector<int> vals;
            do {
                TreeNode *n = s1.top();
                vals.push_back(n->val);
                if (level % 2 != 0) {
                    if (n->left) s2.push(n->left);
                    if (n->right) s2.push(n->right);
                } else { // even level, push right first
                    if (n->right) s2.push(n->right);
                    if (n->left) s2.push(n->left);
                }
                s1.pop();
            } while (!s1.empty());
            level ++;
            res.push_back(vals);
            // swap s1 and s2
            s1.swap(s2);
        }
        return res;
    }
};
#endif
